<template>
  <div class="container">
    <el-card class="box-card">
      <div class="title">团油商户端管理系统</div>
      <div class="check-box">
        <div class="account-title-wrap" :class="{right: index === 1}" v-for="(item,index) in titleArr" :key="index" @click="switchLogin(index)">
          <div class="account-title-text" :class="{check:currentIndex === index}">
            {{item}}
          </div>
        </div>
      </div>
      <!-- 账号登陆 -->
      <el-form :model="loginOptions" ref="accountForm" :rules="accountRules" class="form" v-if="loginType === 0">
        <el-form-item  prop="account">
          <el-input v-model.trim="loginOptions.account" autocomplete="off" placeholder="账号" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item  prop="password" class="item">
          <el-input type="password" v-model.trim="loginOptions.password" maxlength="30" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item class="check-item">
          <el-checkbox v-model="loginOptions.isCheckByAccount" size="mini"><span class="auto">自动登录</span></el-checkbox>
        </el-form-item>
        <el-form-item class="btn-item">
          <el-button type="primary"  @click="toLogin('accountForm')">登录</el-button>
        </el-form-item>
      </el-form>
      <!-- 手机登陆 -->
      <el-form :model="phoneOptions" ref="phoneForm" class="form" :rules="rules" v-else>
        <el-form-item  prop="mobile">
          <el-input type="tel"  v-model.trim="phoneOptions.mobile" autocomplete="off" placeholder="手机号" maxlength="11" readonly @focus="removeAttr"></el-input>
        </el-form-item>
        <el-form-item  prop="verificationCode" class="item">
          <el-input type="text" style="width: 59%;margin-right: 12px" v-model.trim="phoneOptions.verificationCode"  maxlength="4" autocomplete="off" placeholder="验证码" readonly @focus="removeAttr"></el-input>
          <el-button @click="toSendCode" type="primary" :disabled="isSending" class="btn" :style="{width: '36%', height: '30px', padding: paddingType[0], backgroundColor: paddingType[1],borderRadius: '1px',border:'none', color: paddingType[2]} " ><span style="font-size: 12px">{{codeText}}</span></el-button>
        </el-form-item>
        <el-form-item class="check-item">
          <el-checkbox v-model="phoneOptions.isCheck" size="mini"><span style="font-size: 12px;color:rgba(102,102,102,0.7); ">自动登录</span></el-checkbox>
        </el-form-item>
        <el-form-item class="btn-item">
          <el-button type="primary"  @click="toLogin('phoneForm')">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { sendCode, loginByPhone, loginByAccount } from '@/api/login'
import { validPhone } from '@/utils/utils'
import MD5 from 'md5'
let URL = require('url')
export default {
  name: 'login',
  data () {
    let checkFunc = (type) => {
      return (rule, value, callback) => {
        if (!value) {
          return callback(new Error(`请输入${type}`))
        } else {
          if (type === '手机号码' ? validPhone(value) : (value.length <= 30 && value.length >= 6)) {
            callback()
          } else {
            return callback(new Error(type === '手机号码' ? `${type}格式不正确` : `${type}为6-30字符`))
          }
        }
      }
    }
    let checkNoEmpyt = (type) => {
      return (rule, value, callback) => {
        if (!value) {
          return callback(new Error(`请输入${type}`))
        } else {
          callback()
        }
      }
    }
    return {
      loginType: 0, // 0 账号/手机号登录  1 手机验证码登录
      currentIndex: 0,
      titleArr: ['账户密码登录','手机号登录'],
      phoneOptions: {
        mobile: '', // 手机
        verificationCode: '', // 验证码
        isCheck: true // 是否自动登录
      },
      loginOptions: {
        account: '', // 账户
        password: '', // 密码
        isCheckByAccount: true
      },
      codeText: '获取验证码',
      rules: {
        mobile: [
          { validator: checkFunc('手机号码'), trigger: 'blur' }
        ],
        verificationCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      accountRules: {
        account: [
          { validator: checkNoEmpyt('账号'), trigger: 'blur' }
        ],
        password: [
          { validator: checkFunc('密码'), trigger: 'blur' }
        ]
      },
      isSending: false,
      token: null
    }
  },
  mounted () {
    this.init()
    // 从url上获取token，用于判断是否是从宙斯跳转过来，如果存在token则自动登陆
    const token = URL.parse(location.href).query
    console.log(token)
    if (token) {
      this.token = token.split('=')[1]
      this.accountLogin()
    }
  },
  computed: {
    paddingType () {
      let {isSending} = this
      if (isSending) {
        return ['0','#F4F4F5','#4B7EFE']
      } else {
        return ['0 10px 0 10px','#4B7EFE','#fff']
      }
    }
  },
  methods: {
    init () {
      this.phoneOptions = {
        mobile: '',
        verificationCode: '',
        isCheck: true
      }
      this.loginOptions = {
        account: '',
        password: '',
        isCheckByAccount: true
      }
    },
    clearValidate(formName) {
      this.$refs[formName].clearValidate() // 切换验证时清除验证
    },
    resetForm(formName) {
      this.$refs[formName].resetFields() // 重置表单
    },
    switchLogin (index) {
      this.currentIndex = index
      this.loginType = index
      if (!index) {
        this.resetForm('phoneForm')
        this.clearValidate('phoneForm')
      } else {
        this.resetForm('accountForm')
        this.clearValidate('accountForm')
      }
    },
    toLogin (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (formName === 'phoneForm') {
            this.login()
          } else {
            this.accountLogin()
          }
        } else {
          return false
        }
      })
    },
    toSendCode () {
      this.$refs.phoneForm.validateField('mobile', errMsg => {
        if (errMsg) {
          return false
        } else {
          this.sendCode()
        }
      })
    },
    async sendCode () {
      let { phoneOptions: { mobile } } = this
      try {
        const { code } = await sendCode({ mobile })
        if (code !== 200) return
        this.isSending = true
        this.setCountText()
      } catch (error) {
        console.log(error.message)
      }
    },
    setCountText () {
      this.codeText = '60s后重新发送'
      let count = 60
      let timer = setInterval(() => {
        this.codeText = `${count}s后重新发送`
        if (count === 0) {
          clearInterval(timer)
          this.isSending = false
          this.codeText = '获取验证码'
        } else {
          count--
          this.codeText = `${count}s后重新发送`
        }
      }, 1000)
    },
    async login () { // 手机号验证码登录
      let { isCheck, ...params } = { ...this.phoneOptions }
      try {
        const { code, result } = await loginByPhone({ ...params })
        if (code !== 200) return
        const { token, ...userInfo } = result
        // localStorage.setItem('loginInfo', JSON.stringify(result || {}))
        await this.$store.dispatch('user/setTokenAndUserInfo', { token: token, auto: isCheck, userInfo })
        this.$router.push({ path: '/' })
      } catch (error) {
        console.log(error.message)
      }
    },
    async accountLogin () { // 账号密码登录
      let { isCheckByAccount, ...params } = { ...this.loginOptions }
      params.password = MD5(params.password)
      // 如果存在token则使用token登陆
      if (this.token) params = { token: this.token }

      try {
        const { code, result } = await loginByAccount(params)
        if (code !== 200) {
          if (this.token) {
            this.$alert('自动登陆失败，请输入账号密码', '提示', {
              confirmButtonText: '确定',
              type: 'error',
              showClose: false,
              showCancelButton: false
            }).then(() => {
              this.token = null
              this.$router.replace({ path: '/login' })
            })
          }
          return
        }
        const { token, ...userInfo } = result
        // localStorage.setItem('loginInfo', JSON.stringify(result || {}))
        await this.$store.dispatch('user/setTokenAndUserInfo', { token: token, auto: isCheckByAccount, userInfo })
        this.$router.push({ path: '/' })
      } catch (error) {
        console.log(error.message)
      }
    },
    removeAttr (e) {
      e.target.removeAttribute('readonly')
    }
  }
}
</script>
<style lang="less" scoped>
  .container{
    width: 100%;
    height: 100%;
    background-image: url('https://weber-imgs.oss-cn-beijing.aliyuncs.com/ty/merchant/image/logo/login_back_img.png');
    background-size: cover;
    background-repeat: no-repeat;
    position: relative;
    .box-card{
      position: absolute;
      background-color: #fff;
      width: 375px;
      top: 170px;
      right: 54px;
      padding: 24px 59px 29px 59px;
      box-sizing: border-box;
      .title{
        text-align: center;
        margin-bottom: 35px;
        font-size:16px;
        font-family:PingFangSC-Medium,PingFang SC;
        font-weight:500;
        color:rgba(34,34,34,1);
        line-height:18px
      }
      .check-box{
        display: flex;
        width: 100%;
        font-size:15px;
        font-family:PingFangSC-Regular,PingFang SC;
        font-weight:bold;
        .account-title-wrap{
          flex: 1;
          width: 50%;
          text-align: left;
          cursor: pointer;
          &.right{
            text-align: right;
          }
          .account-title-text{
            color:rgba(34,34,34,1);
            line-height:18px;
            font-weight:500;
            font-family:PingFangSC-Regular,PingFang SC;
            &.check{
              color:rgba(75,126,254,1);
            }
          }
        }
      }
      .form{
        margin-top: 19px;
        .item{
          position: relative;
          margin-bottom: 0px;
          .btn{
            position: absolute;
            right: 0;
            bottom: 0;
          }
        }
        .check-item{
          margin-top: 5px;
          margin-bottom: 19px;
          .auto {
            font-size: 12px;
            color:rgba(102,102,102,0.7);
          }
        }
        .btn-item{
          margin-bottom: 0px;
          /deep/.el-button {
            width: 100%;
            height: 38px;
            padding: 0px 10px 0 10px;
            background-color: #4B7EFE;
            border-radius: 2px;
            border: none;
          }
        }
      }
    }
  }


/deep/.el-input__inner {
  display: inline-block;
	border-top-width: 0px;
	border-left-width: 0px;
	border-right-width: 0px;
  border-bottom-width: 1px;
  border-radius: 0;
  padding: 0;
  &::placeholder{
    font-size: 12px;
  }
	&::-webkit-input-placeholder{
    font-size: 12px;
  }
  &:-moz-placeholder{
    font-size: 12px;
  }
  &::-moz-placeholder{
    font-size: 12px;
  }
  &:-ms-input-placeholder{
    font-size: 12px;
  }
}

/deep/ .el-checkbox__inner {
  width: 10px;
  height: 10px;
  line-height: 15px;
  &::after{
    left: 3px;
    top: -1px;
  }
}
/deep/.el-checkbox__label{
  padding-left: 4px;
}
/deep/.el-card__body{
  padding: 0;
}
/deep/.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #4B7EFE;
  border-color: #4B7EFE;
}
</style>
